'/
' listext.bmx
' 
' Originally written by Plash.
' Found at the Code Archives at:
'    http://www.blitzmax.com/
' 
' Additional code written by Anthony Berlin.
' 
' Declared as public domain.
'/

superstrict

import BRL.LinkedList

type listext

	function listAppendList:int(dest:TList, from:TList)
	
		local copy:TList;
		
		if (dest = null or from = null or not from.count()) ..
			return false;
		
		copy = from.copy();
		insertListBeforeLink(copy, dest._head);
		
		return true;
	
	end function
	
	function insertListBeforeLink(thislist:TList, beforethis:TLink)
	
		local this:TLink = thislist.FirstLink();
		local last:TLink = thislist.lastLink();
		
		this._pred = beforethis._pred;
		this._pred._succ = this;
		last._succ = beforethis;
		beforethis._pred = last;
	
	end function
	
	function moveObjectUp:int(list:TList, obj:object)
	
		local link:TLink;
		local prev:TLink;
		
		if (not list.count()) ..
			return false;
		
		link = list.findLink(obj)
		
		if (link = null) ..
			return false;
		
		prev = link.prevLink()
		
		if (prev = null) ..
			return false; '// Already at the top of the list.
		
		link = null;
		list.remove(obj);
		list.insertBeforeLink(obj, prev);
		
		return true;
		
	end function
	
	function moveObjectDown:int(list:TList, obj:object)
	
		local link:TLink;
		local nextlink:TLink;
		
		if (not list.count()) ..
			return false;
		
		link = list.findLink(obj)
		
		if (link = null) ..
			return false;
		
		nextlink = link.nextLink()
		
		if (nextlink = null) ..
			return false; '// Already at the bottom of the list.
		
		link = null;
		list.remove(obj);
		list.insertAfterLink(obj, nextlink);
		
		return true;
		
	end function

end type
